package com.recruit.g1.basic.service.impl;

import java.util.List;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.recruit.g1.basic.dao.repository.AreaRepository;
import com.recruit.g1.basic.pojo.po.AreaPO;
import com.recruit.g1.basic.pojo.vo.AreaVO;
import com.recruit.g1.basic.service.AreaService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.nacos.common.utils.CollectionUtils;
import org.springframework.stereotype.Service;

@Service
public class AreaServiceImpl  implements AreaService {
    @Autowired
    private AreaRepository areaRepository;
    //不管接口 如何和前端交互 调用业务层逻辑相同的
    //查询省parentId=0 查询市parentId=#{省id} 查询区 parentId#{市id}
    public List<AreaVO> getChildren(Integer parentId){
        QueryWrapper<AreaPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId);
        List<AreaPO> pos = areaRepository.list(queryWrapper);
        return pos.stream().map(po->{
            AreaVO vo=new AreaVO();
            BeanUtils.copyProperties(po,vo);
            return vo;
        }).collect(Collectors.toList());
    }


    //手动封装 3000多个行政区域的3级树

    /*@Override
    public List<AreaVO> getAreaList(Integer parentId) {
        return Collections.emptyList();
    }*/

    public List<AreaVO> tree() {
        //VERSION1 暂时不关心树结构,返回list包含的省级行政区列表
        //select * from lbs_area where parent_id=0
        //VERSION2 对省级列表循环得到每个省的市,嵌套循环 对市列表循环得到每个市的区
        List<AreaPO> all = areaRepository.list();
        List<AreaPO> provincePos = all.stream().filter(po -> po.getParentId() == 0).collect(Collectors.toList());
        //将pos转化vos的过程封装成私有方法 以便于后续查询市,区转化
        List<AreaVO> provinceVos=pos2vos(provincePos);
        for (AreaVO provinceVo : provinceVos) {
            Long provinceId=provinceVo.getId();
            //获取每个省里面的市列表
            List<AreaPO> cityPos = all.stream().filter(po -> po.getParentId() .equals(provinceId)).collect(Collectors.toList());
            //cityPos转化成cityVos交给procinceVO.setChildren();
            List<AreaVO> cityVos = pos2vos(cityPos);
            for (AreaVO cityVo : cityVos) {
                Long cityId = cityVo.getId();
                List<AreaPO> areaPos = all.stream().filter(po -> po.getParentId().equals(cityId)).collect(Collectors.toList());
                cityVo.setChildren(pos2vos(areaPos));
            }
            provinceVo.setChildren(cityVos);
        }
        return provinceVos;
    }

    public List<AreaVO> pos2vos(List<AreaPO> provincePos) {
        if (CollectionUtils.isNotEmpty(provincePos)){
            return provincePos.stream().map(po->{
                AreaVO vo=new AreaVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }else{
            //入参po是空
            return null;
        }
    }


}
